<template>
  <div class="search">
    <div class="header">
      <van-search
        v-model="keyword"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
      >
      <template #left>
        <i  @click="$router.back()" class="iconfont iconjiantou"></i>
      </template>
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
      </van-search>
    </div>
  <!-- 2.0 历史记录和搜一搜 -->
  <div class="group"
    v-show="!searchList.length"
  >
    <div class="title">
      <h3>历史记录</h3>
      <van-icon @click="keywordArr=[]" name="delete-o" />
    </div>
    <div class="list">
      <span class="item"
        v-for="(item,index) in keywordArr"
        :key="index"
        @click="btnFn(item)"
      >{{item}}</span>
    </div>
  </div>
  <!-- 3.0 搜索结果面板 -->
  <div class="result"
    v-show="searchList.length"
  >
    <router-link 
      class="item"
      v-for="item in searchList"
      :key="item.id"
      :to="`/article/${item.id}`"
    >
      <span class="text">{{item.title}}</span>
      <i class="iconfont iconjaintou1"></i>
    </router-link>
  </div>
  </div>
</template>

<script>
import {getPostSearchAPI} from '../apis/news'
import {getSearchKeyword,setSearchKeyword} from '../utils/localData'
export default {
  data () {
    return {
      keyword:"",
      searchList:[],
      keywordArr:getSearchKeyword(),
    }
  },
  methods:{
  async onSearch() {
      if(this.keyword === '') {
        return this.$toast.fail('请输入关键字')
      }
      // 按搜索后
      this.keywordArr.unshift(this.keyword);
      // 数组去重
      this.keywordArr = [...new Set(this.keywordArr)]
      // 限制搜索历史记录最大10条
      if(this.keywordArr.length >= 10) {
        this.keywordArr.length = 10;
        // this.keywordArr.pop()
      }
      const res = await getPostSearchAPI({
        keyword:this.keyword,
      });
      // console.log(res);
      // this.keyword = ""
      this.searchList = res.data.data
    },
    btnFn(theItem) {
      this.keyword = theItem;
      this.onSearch();
    }
  },
  watch:{
    // 如果搜索为空
    keyword() {
      if(this.keyword ==='') {
        // 清空数组
        this.searchList = [];
      }
    },
    // 监听搜索关键字数组
    keywordArr() {
      setSearchKeyword(this.keywordArr)
    }
  }
}
</script>

<style lang="less" scoped>
.group {
  padding: 10px;
  .title {
    font-size: 16px;
    margin: 10px 0;
    display: flex;
    justify-content: space-between;
  }

  .list {
    display: flex;
    flex-wrap: wrap;
    .item {
      padding: 5px;
      font-size: 13px;
      margin-right: 10px;
      border: 1px solid #ccc;
    }
  }
}
.result {
  .item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px;
    border-bottom: 1px solid #ccc;
  }
  .text{
    color: #000;
  }
}
</style>
